<!-- 代码已包含 CSS：使用 TailwindCSS , 安装 TailwindCSS 后方可看到布局样式效果 -->

<template>
  <div class="min-h-screen bg-[#1E2128] flex items-center justify-center py-12 px-4 sm:px-6 lg:px-8">
    <div class="max-w-md w-full space-y-8 bg-[#282C34] bg-opacity-50 p-8 rounded-lg">
      <div>
        <h2 class="text-center text-3xl font-bold text-white mb-2">蓝蚁智控</h2>
        <p class="text-center text-gray-400 text-sm">专业的企业级AI数字人口矩阵解决方案</p>
      </div>
      <form class="mt-8 space-y-6" @submit.prevent="handleSubmit">
        <div class="space-y-4">
          <div>
            <input v-model="form.username" type="text" class="appearance-none rounded-md relative block w-full px-3 py-2 border border-gray-700 bg-[#1E2128] bg-opacity-50 text-white placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent" placeholder="用户名" @input="validateUsername" />
            <p v-if="errors.username" class="mt-1 text-sm text-red-500">{{ errors.username }}</p>
          </div>


          <div class="relative">
            <input v-model="form.password" :type="showPassword ? 'text' : 'password'" class="appearance-none rounded-md relative block w-full px-3 py-2 border border-gray-700 bg-[#1E2128] bg-opacity-50 text-white placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent" placeholder="密码" @input="validatePassword" />
            <button type="button" class="absolute inset-y-0 right-0 pr-3 flex items-center" @click="togglePassword">
              <i :class="showPassword ? 'fas fa-eye-slash' : 'fas fa-eye'" class="text-gray-400"></i>
            </button>

          </div>
          <p v-if="errors.password" class="mt-1 text-sm text-red-500">{{ errors.password }}</p>
          <div>
            <input v-model="form.contact_phone" type="text" class="appearance-none rounded-md relative block w-full px-3 py-2 border border-gray-700 bg-[#1E2128] bg-opacity-50 text-white placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent" placeholder="手机号" @input="validatePhone" />
            <p v-if="errors.contact_phone" class="mt-1 text-sm text-red-500">{{ errors.contact_phone }}</p>
          </div>
<!--          <div>-->
<!--            <input v-model="form.contact_mail" type="text" class="appearance-none rounded-md relative block w-full px-3 py-2 border border-gray-700 bg-[#1E2128] bg-opacity-50 text-white placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent" placeholder="邮箱" @input="validatecontact_mail" />-->
<!--            <p v-if="errors.contact_mail" class="mt-1 text-sm text-red-500">{{ errors.contact_mail }}</p>-->
<!--          </div>-->

<!--          <div>-->
<!--            <input v-model="form.contact_wechat" type="text" class="appearance-none rounded-md relative block w-full px-3 py-2 border border-gray-700 bg-[#1E2128] bg-opacity-50 text-white placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent" placeholder="微信号" />-->
<!--          </div>-->

          <div class="grid grid-cols-2 gap-4">
            <div>
              <select v-model="form.usertype" class="appearance-none rounded-md relative block w-full px-3 py-2 border border-gray-700 bg-[#1E2128] bg-opacity-50 text-white placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                <option value="" disabled selected>请选择类型</option>
                <option value="个人">个人</option>
                <option value="实体">实体</option>
                <option value="工作室">工作室</option>
                <option value="公司">公司</option>
              </select>
            </div>
            <div>
              <input v-model="form.matrix_count" type="number" class="appearance-none rounded-md relative block w-full px-3 py-2 border border-gray-700 bg-[#1E2128] bg-opacity-50 text-white placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent" placeholder="手机矩阵数量" />
            </div>
<!--            <div>-->
<!--              <input v-model="form.scale" type="number" class="appearance-none rounded-md relative block w-full px-3 py-2 border border-gray-700 bg-[#1E2128] bg-opacity-50 text-white placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent" placeholder="规模(人)" />-->
<!--            </div>-->
          </div>


<!--          <div>-->
<!--            <input v-model="form.register_code" type="text" class="appearance-none rounded-md relative block w-full px-3 py-2 border border-gray-700 bg-[#1E2128] bg-opacity-50 text-white placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent" placeholder="邀请码" @input="validateRegisterCode" />-->
<!--            <p v-if="errors.register_code" class="mt-1 text-sm text-red-500">{{ errors.register_code }}</p>-->
<!--          </div>-->
          <div class="flex items-center space-x-4">
            <div class="flex-1">
              <input v-model="form.captcha" type="text" class="appearance-none rounded-md relative block w-full px-3 py-2 border border-gray-700 bg-[#1E2128] bg-opacity-50 text-white placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent" placeholder="验证码" />

            </div>
            <div class="w-32 h-10 bg-gray-700 rounded flex items-center justify-center cursor-pointer" @click="refreshCaptcha">
              <img :src="captchaImage" alt="captcha" class="w-full h-full"/>
<!--              <span class="text-white font-mono text-lg">{{ captchaText }}</span>-->
            </div>

          </div>
          <div v-if="errors.captcha" >
            <p class="mt-1 text-sm text-red-500">{{ errors.captcha }}</p>
          </div>
        </div>
        <div>
          <button type="submit" class="!rounded-button group relative w-full flex justify-center py-2 px-4 border border-transparent text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500">
            注册
          </button>
        </div>
        <div class="flex items-center">

          <label for="agreement" class="ml-2 block text-sm text-gray-400">
            提交注册即代表您同意
            <a href="/yhxy" target="_blank" class="text-blue-500 hover:text-blue-400">用户协议</a>
            和
            <a href="/ystk" class="text-blue-500 hover:text-blue-400">隐私政策</a>
          </label>
        </div>



        <div class="text-center">
          <a href="#" @click="router.push('/login')" class="text-sm text-gray-400 hover:text-blue-500">已有账号？立即登录</a>
        </div>
      </form>
    </div>
  </div>
</template>

<script  setup>
import { ref, reactive } from 'vue';
import {get,post} from "@/utils/api";
import config from "@/config";
import {MessagePlugin} from "tdesign-vue-next";
import router from "@/router";
const captchaImage = ref('');
const getCaptcha = () => {
  //获取验证码
  get(config.captcha).then(res=>{
    console.log("captcha",res.data.data)
    captchaImage.value = res.data.data.image;
    form.uniqid = res.data.data.uniqid;
  })
};
getCaptcha()



const showPassword = ref(false);
const captchaText = ref(generateCaptcha());

const form = reactive({
  username:'',
  contact_phone: '',
  password: '',
  contact_mail: '',
  contact_wechat: '',
  usertype: '',
  scale: '',
  matrix_count: '',
  account_count: '',
  captcha: '',
  register_code:localStorage.getItem('register_code'),
});

const errors = reactive({
  username:'',
  phone: '',
  password: '',
  contact_mail: '',
  captcha: '',
});

function generateCaptcha() {
 // return Math.random().toString(36).substring(2, 8).toUpperCase();
  return Math.floor(100000 + Math.random() * 900000).toString();
}

function refreshCaptcha() {
  getCaptcha()
}

function togglePassword() {
  showPassword.value = !showPassword.value;
}
function validateUsername() {
  const usernameRegex = /^[a-zA-Z0-9]{8,}$/;

  if (!form.username) {
    errors.username = '请输入用户名';
  } else if (form.username.length < 8) {
    errors.username = '用户名长度至少8位';
  } else if (!usernameRegex.test(form.username)) {
    errors.username = '用户名必须由8位及以上英文或数字组成';
  } else {
    errors.username = '';
  }
}
function validateRegisterCode() {
  if (!form.register_code) {
    errors.register_code = '请输入邀请码';
  }  else {
    errors.register_code = '';
  }
}
function validatePhone() {
  const phoneRegex = /^1[3-9]\d{9}$/;
  if (!form.contact_phone) {
    errors.contact_phone = '请输入手机号';
  } else if (!phoneRegex.test(form.contact_phone)) {
    errors.contact_phone = '请输入有效的手机号';
  } else {
    errors.contact_phone = '';
  }
}

function validatePassword() {
  const hasLetter = /[a-zA-Z]/.test(form.password);
  const hasNumber = /[0-9]/.test(form.password);
  const hasSymbol = /[!@#$%^&*()_+=[\]{};':"\\|,.<>/?]/.test(form.password);

  const complexityCount = [hasLetter, hasNumber, hasSymbol].filter(Boolean).length;

  if (!form.password) {
    errors.password = '请输入密码';
  } else if (form.password.length < 8) {
    errors.password = '密码长度至少8位';
  } else if (complexityCount < 2) {
    errors.password = '密码需包含字母、数字、符号中至少两种组合';
  } else {
    errors.password = '';
  }
}

// function validatecontact_mail() {
//   const contact_mailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
//   if (!form.contact_mail) {
//     errors.contact_mail = '请输入邮箱';
//   } else if (!contact_mailRegex.test(form.contact_mail)) {
//     errors.contact_mail = '请输入有效的邮箱地址';
//   } else {
//     errors.contact_mail = '';
//   }
// }

const handleSubmit = async() =>{
  validateRegisterCode()
  validateUsername();
  validatePhone();
  validatePassword();
 // validatecontact_mail();

  // if (!form.agreement) {
  //   alert('请阅读并同意用户协议');
  //   return;
  // }

  // if (form.captcha.toUpperCase() !== captchaText.value) {
  //   errors.captcha = '验证码错误';
  //   return;
  // }else{
  //   errors.captcha = '';
  // }

  if (!errors.phone && !errors.password && !errors.contact_mail) {
    try {
      // 模拟登录请求
      const response = await post(config.register,form); // Adjust API endpoint as needed
      if (response.status === 200) {
        const data = response.data;
        if (data.code === 1) {
          MessagePlugin.success(data.info);
          router.push("/login");
        }else{
          MessagePlugin.error(data.info);
          getCaptcha()
        }
      } else {
        MessagePlugin.error('Failed to fetch feedback data');
        getCaptcha()
      }
      // 这里添加实际的登录逻辑
    } catch (error) {
      MessagePlugin.error('注册失败:', error);
      getCaptcha()
    }
    console.log('Form submitted:', form);
  }
}
</script>

<style scoped>
input[type="number"]::-webkit-inner-spin-button,
input[type="number"]::-webkit-outer-spin-button {
  -webkit-appearance: none;
  margin: 0;
}

input[type="number"] {
  -moz-appearance: textfield;
}

select {
  background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 20 20'%3e%3cpath stroke='%236b7280' stroke-linecap='round' stroke-linejoin='round' stroke-width='1.5' d='M6 8l4 4 4-4'/%3e%3c/svg%3e");
  background-position: right 0.5rem center;
  background-repeat: no-repeat;
  background-size: 1.5em 1.5em;
  padding-right: 2.5rem;
  -webkit-print-color-adjust: exact;
  print-color-adjust: exact;
}
</style>

